//用户信息获取/修改

import { Request, Response, NextFunction } from 'express';
import * as userService from '../services/user.service';
import { UpdateUserDTO } from '../dto/user.dto';
import { userToClient } from '../utils/user';
import { HttpError } from '../utils/httpError';
import { ErrorCode } from '../constants/errorCode';

export const getProfile = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const id = Number((req as any).user.id);
    const user = await userService.getUserById(id);
    if (!user) throw new HttpError(ErrorCode.USER_NOT_FOUND, 404);
    res.safeJson(userToClient(user), '获取成功');
  } catch (err) {
    next(err);
  }
};

export const updateProfile = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const input = UpdateUserDTO.parse(req.body);
    const id = Number((req as any).user.id);
    const updated = await userService.updateUser(id, input);
    res.safeJson(userToClient(updated), '更新成功');
  } catch (err) {
    next(err);
  }
};
